/*
 * PacketVector.java
 *
 * Created on April 15, 2008, 10:18 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.sunspotworld.datawrappers;

import com.sun.spot.peripheral.IDriver;
import com.sun.spot.peripheral.Spot;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import org.sunspotworld.mydatawrappers.NeighborPacket;
import org.sunspotworld.mydatawrappers.TrackingPacketFactory;

/**
 * A Singleton vector to contain IDataWrappers
 * @author Douglas McClusky
 */
public class DataWrapperVector implements IDriver {
    private static DataWrapperVector vector = new DataWrapperVector();
    private RecordStore rec;
    private Vector vec;
    private static final String REC_KEY = "DataWrapperVector";
    private RecordEnumeration ren;
    private NeighborPacket currentBeaconRecord;
    private int maxSize;
    private double flashRate = .5;
    
    /** Creates a new instance of PacketVector */
    private DataWrapperVector() {
        currentBeaconRecord = new NeighborPacket();
        maxSize = 0;
        
        //create Vector from recordstore
        vec = new Vector();
        
        try {
            rec = RecordStore.openRecordStore(REC_KEY, true);
            ren = rec.enumerateRecords(null, null, false);
            while (ren.hasNextElement()) {
                int id = ren.nextRecordId();
                add(TrackingPacketFactory.getInstance().constructDataWrapper(rec.getRecord(id)));
                rec.deleteRecord(id);
            }
            rec.closeRecordStore();
            if (Spot.getInstance().getPersistentProperty("PowerDown") == null || Spot.getInstance().getPersistentProperty("PowerDown").equals("false")) {
                RecordStore.deleteRecordStore(REC_KEY);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        } 
        String rate = Spot.getInstance().getPersistentProperty("FlashRate");
        if (rate != null) {
            flashRate = Double.parseDouble(rate);
        }
        Spot.getInstance().getDriverRegistry().add(this);
    }
    
    public int getMaxSize() {
        return maxSize;
    }
    
    public long[] getLastNeighbors() {
        return currentBeaconRecord.getAddresses();
    }
    
    public void addAddress(long addr) {
        currentBeaconRecord.addAddress(addr);
    }
    
    public void startNewNeighborRecord() {
        if (!currentBeaconRecord.isEmpty()) {
        add(currentBeaconRecord);
        }
        currentBeaconRecord = new NeighborPacket();
    }
    
    /**
     * Add an IDataWrapper to the vector
     * @param pkt
     */
    public void add (DataWrapper pkt) {
        vec.addElement(pkt);
        this.maxSize = Math.max(maxSize, pkt.getSize());
        System.out.println(pkt.printEntryLine());
    }
    
    /**
     * Get an Enumeration of all the IDataWrappers added to this vector
     * @return
     */
    public DataWrapper dequeue() {
        if (vec.isEmpty()) {
            return null;
        }
        DataWrapper pkt = (DataWrapper)vec.firstElement();
        vec.removeElementAt(0);
        return pkt;
    }
    
    public void clearVector() {
        vec = new Vector();
    }
    
    /**
     * @return the Singleton instance of DataWrapperVector
     */
    public static DataWrapperVector getInstance() {
        return vector;
    }
    
    /**
     * @return whether the vector has no IDataWrappers in it
     */
    public boolean isEmpty() {
        return vec.isEmpty();
    }

    public String getDriverName() {
        return "DataVector";
    }

    public boolean tearDown() {
        return true;
    }

    public void setUp() {
    }

    public void shutDown() {
        try {
            long start = System.currentTimeMillis();
            //write Vector to recordstore
            rec = RecordStore.openRecordStore(REC_KEY, true);
            for (int i = 0; i < vec.size(); i++) {
                DataWrapper pkt = (DataWrapper)vec.elementAt(i);
                rec.addRecord(pkt.toByteArray(), 0, pkt.getSize());
            }
            Spot.getInstance().setPersistentProperty("FlashRate", "" + (System.currentTimeMillis()-start)/(vec.size()+0.0));
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        } 
    }
    
    public double shutDownPowerNeeded() {
        return Spot.getInstance().getPowerController().getIdischarge()*(vec.size()*flashRate + 200)/3600000;
    }
}
